package cn.wolfcode.trip.base.util;

import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.MatchRequest;
import org.json.JSONObject;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;

public class FaceUtil {

    //设置APPID/AK/SK
    public static final String APP_ID = "15455016";
    public static final String API_KEY = "psC3s1HkvilYete2KL9rGCHI";
    public static final String SECRET_KEY = "MN1ew7EM5s01mfSLoX1k70tnHK0ylMGp";

    public static boolean compareFace(String facePath) {
        // 初始化一个AipFace
        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        String image1 = GetImageStr("E:/face/liangzai.jpg");
        String image2 = GetImageStr(facePath);

        // image1/image2也可以为url或facetoken, 相应的imageType参数需要与之对应。
        MatchRequest req1 = new MatchRequest(image1, "BASE64");
        MatchRequest req2 = new MatchRequest(image2, "BASE64");
        ArrayList<MatchRequest> requests = new ArrayList<MatchRequest>();
        requests.add(req1);
        requests.add(req2);

        JSONObject res = client.match(requests);
        System.out.println(res);
        if (res.getJSONObject("result").getDouble("score")>80) {
            return true;
        }
        return false;
    }

    public static String uploadFile(String fileData,String imgPath)  {

        //使用BASE64对图片文件数据进行解码操作
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            //通过Base64解密，将图片数据解密成字节数组
            byte[] bytes = decoder.decodeBuffer(fileData);
            //构造字节数组输入流
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            //读取输入流的数据
            BufferedImage bi = ImageIO.read(bais);
            //将数据信息写进图片文件中
            ImageIO.write(bi, "jpg", new File(imgPath));// 不管输出什么格式图片，此处不需改动
            bais.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return imgPath;
    }

    public static String GetImageStr(String imgFile)
    {//将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try
        {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);//返回Base64编码过的字节数组字符串
    }

}
